package com.dh.shiro.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dh.shiro.entity.User;

/** 
 * @author 作者 dinghao
 * @version 创建时间：2018年11月26日 下午3:45:43 
 * @Description 类说明 :
 */
@RestController
public class TestController {
	
	@Resource(name = "rootUser")
	private User user;

	@GetMapping("/index")
	public String index() {
		return "index";
	}
	
	@GetMapping("/admin")
	public String admin() {
		return "ADMIN";
	}
	
	@GetMapping("/edit")
	public String edit() {
		return "edit";
	}
	
	@PostMapping("/loginUser")
	public String loginUser(@RequestParam("username") String username,@RequestParam("password")String password,HttpSession session) {
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			User user = (User) subject.getPrincipal();
			session.setAttribute("user", user);
			return "index";
		} catch (Exception e) {
			return "login";
		}
	}
	
	@GetMapping("/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		if(subject != null) {
			subject.logout();
		}
		return "logout";
	}
}
